//
//  AppDelegate.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/2.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    let BuglyAppID = "161c9ae157"

    var window: UIWindow?
    
    var launchVc: JKLaunchViewController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        Bugly.start(withAppId: BuglyAppID)
        
        // 注册微信、微博
        WXApi.registerApp(JKWXAppkey, universalLink: "")
        WeiboSDK.registerApp(JKWeiboAppKey)
        
        window = UIWindow(frame: UIScreen.main.bounds)
        
        launchVc = JKLaunchViewController()
        
        window?.rootViewController = launchVc
        
        window?.makeKeyAndVisible()
        
        // 打开数据库
        JKSQLiteManager.shared.openDB(dbName: "story.sqlite")
        
        // 程序启动后，判断是否有超过7天的数据，如果有，则删除
        JKSQLiteManager.clearData()
        
        add3DTouch()
        
        if #available(iOS 9.0, *) {
            
            if launchOptions != nil {
                
                if let item = launchOptions![UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
                    
                    launchVc?.jumpTo = (item.type == "1") ? "最新日报" : "最新瞎扯"
                }
            }
            
        } else {
            // Fallback on earlier versions
        }
        
        return true
    }
    
    /** add3DTouch */
    private func add3DTouch() {
        
        if #available(iOS 9.0, *) {
            
            let icon1 = UIApplicationShortcutIcon(type: UIApplicationShortcutIconType.share)
            let item1 = UIApplicationShortcutItem(type: "1", localizedTitle: "最新日报", localizedSubtitle: nil, icon: icon1, userInfo: nil)
            
            let icon2 = UIApplicationShortcutIcon(type: UIApplicationShortcutIconType.compose)
            let item2 = UIApplicationShortcutItem(type: "2", localizedTitle: "最新瞎扯", localizedSubtitle: nil, icon: icon2, userInfo: nil)
            
            UIApplication.shared.shortcutItems = [item1, item2]
            
        } else {
            
        }
            
    }
    
    @available(iOS 9.0, *)
    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        
        if application.keyWindow?.rootViewController is JKLaunchViewController {
            
            launchVc?.jumpTo = (shortcutItem.type == "1") ? "最新日报" : "最新瞎扯"
            
        }else if application.keyWindow?.rootViewController is JKMainViewController {
            
            (application.keyWindow?.rootViewController as! JKMainViewController).jumpTo = (shortcutItem.type == "1") ? "最新日报" : "最新瞎扯"
        }
        
        completionHandler(true);
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        return WXApi.handleOpen(url, delegate: JKShareManager.shared) || WeiboSDK.handleOpen(url, delegate: JKShareManager.shared)
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        return WXApi.handleOpen(url, delegate: JKShareManager.shared) || WeiboSDK.handleOpen(url, delegate: JKShareManager.shared)
    }
}


/**
 打印LOG的弊端：
 1.非常消耗性能
 2.如果app部署到AppStoree之后，用户是看不到LOG的
 
 所以
 开发阶段：显示LOG
 部署阶段：隐藏LOG
 */

// 定义在类的大括号外面的函数就是全局函数，如果写在一个类大括号里面，就是这个类的函数，只能通过该类执行函数
// 函数的默认值：如果调用者没有传递对应的参数，那么系统就会使用默认值，如果调用者传递了参数，那么就会使用传入的参数
/**
 由于编译器可以通过赋值的类型自动推导出数据的真实类型，所以在Swift开发中，能不写数据类型就不写数据类型
 优点：可以减少冗余代码
 */
/**
 泛型
 如果想在函数中使用泛型，那么必须告诉系统这是一个泛型函数
 注: 尖括号中可以随便填，但是一般就是写个T。表示泛型形参名的类型就是T类型，即传入什么类型就是什么类型
 func 函数名<T>(泛型形参名: T) -> 返回值 {
 }
 */
// T具体是什么类型由调用者决定，调用者传入什么类型，T就是什么类型
public func JKLog<T>(message: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line){
    
    #if DEBUG // Build Settings 搜索custom flag -> 给Debug添加一个自定义标记 -D DEBUG
        // 获得和QorumLogs一样的打印输出
        // AppDelegate.application(_:didFinishLaunchingWithOptions:).53:[;打印的内容
        //print("\((fileName as NSString).pathComponents.last!.componentsSeparatedByString(".").first!).\(methodName).\(lineNumber):\(message)")
        
        // 只需要函数名和行号就行了，没必要打印类名了，太长
        if let className = (URL(string: fileName)?.lastPathComponent.split(separator: ".").first) {
            
            print("\(className)  \(methodName)  \(lineNumber): \(message)\n")
            
        }else{
            
            print("\(methodName)  \(lineNumber): \(message)\n")
        }
        
        
    #endif
}

/** CGRectMake */
public func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
    
    return CGRect(x: x, y: y, width: width, height: height)
}

public func CGPointMake(_ x: CGFloat, _ y: CGFloat) -> CGPoint {
    
    return CGPoint(x: x, y: y)
}

public func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
    
    return CGSize(width: width, height: height)
}



/** CGAffineTransformMake */
public func CGAffineTransformMakeScale(_ scaleX: CGFloat, _ y: CGFloat) -> CGAffineTransform {
    
    return CGAffineTransform(scaleX: scaleX, y: y)
}

public func CGAffineTransformMakeTranslation(_ tx: CGFloat, _ ty: CGFloat) -> CGAffineTransform {
    
    return CGAffineTransform(translationX: tx, y: ty)
}

public func CGAffineTransformTranslate(_ transform: CGAffineTransform, _ tx: CGFloat, _ ty: CGFloat) -> CGAffineTransform {
    
    return transform.translatedBy(x: tx, y: ty)
}

public func CGAffineTransformScale(_ transform: CGAffineTransform, _ scaleX: CGFloat, _ y: CGFloat) -> CGAffineTransform {
    
    return transform.scaledBy(x: scaleX, y: y)
}


